package com.gym.myshop.dao.impl;

import com.gym.myshop.dao.UserDao;
import com.gym.myshop.entity.User;
import com.gym.myshop.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author ming
 * 2021/11/3
 * description:
 */
public class UserDaoImpl implements UserDao {

    private QueryRunner qr = new QueryRunner();



    /**
     *@author:ming
     *@Date: 2021/11/4
     *@description:查user全部数据
     */
    @Override
    public List<User> getAllUser() {
        try {
            return qr.query(DBUtil.getConnection(), "select * from user ", new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *@author:ming
     *@Date: 2021/11/4
     *@description:用户名查找判断
     */
    @Override
    public User getUserByName(String username) {

        try {
            return qr.query(DBUtil.getConnection(), "select * from user where uname = ?", new BeanHandler<>(User.class), username);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     *@author:ming
     *@Date: 2021/11/4
     *@description:注册信息添加
     */
    @Override
    public int addUser(User u) {
        try {
            return qr.update(DBUtil.getConnection(),
                    "insert into user values (default,?,?,?,?,?,?,?)",
                    u.getUname(),u.getUpassword(),u.getUemail(),u.getUsex()
                    ,u.getUstatus(),u.getUcode(),u.getUrole()
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     *@author:ming
     *@Date: 2021/11/5
     *@description:用户不存在，无法激活
     */
    @Override
    public User getUserByEmailAndCode(String e, String c) {
        try {
            return qr.query(DBUtil.getConnection(),"select * from user where uemail = ? and ucode = ?",
                    new BeanHandler<>(User.class),e,c);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return null;
    }


    /**
     *@author:ming
     *@Date: 2021/11/5
     *@description:用户已激活过
     */
    @Override
    public int updateUserStatus(int activate, int uid) {
        try {
            return qr.update(DBUtil.getConnection(),
                    "update user set ustatus = ? where uid= ?",
                    activate,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }


}
